package com.mirror.tk.api.controller;

import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.google.common.collect.Lists;
import com.mirror.tk.api.common.Constant;
import com.mirror.tk.api.common.support.JwtFace;
import com.mirror.tk.api.common.support.JwtUser;
import com.mirror.tk.core.module.sys.domain.SysAttachment;
import com.mirror.tk.core.module.sys.dto.DictionariesDto;
import com.mirror.tk.core.module.sys.dto.UploadDto;
import com.mirror.tk.core.module.sys.service.BasicService;
import com.mirror.tk.core.module.sys.service.SysAttachmentService;
import com.mirror.tk.framework.common.web.support.JsonListResult;
import com.mirror.tk.framework.common.web.support.JsonResult;
import com.mirror.tk.framework.utils.Collections3;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 全局公用接口（可以任意调用，接口权限自行确定）
 */
@Api(value = "全局公用API", description = "提供全局公用的方法，权限具体查看各方法")
@RestController
@RequestMapping("global")
public class GlobalControler extends CommonController {

	@Resource
	private SysAttachmentService attachmentService;
	@Resource
	private BasicService basicService;

	@ApiOperation(value = "附件上传", notes = "该接口需要用户登录，不然无法上传。需要上传关联模块，以便区分附件")
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public JsonListResult<SysAttachment> upload(HttpServletRequest request, HttpServletResponse response, 
			@ApiParam(value = "附件模块", required = true)@RequestParam(value = "key", required = true)String relationKey) {
		JsonListResult<SysAttachment> result = new JsonListResult<SysAttachment>();
		// 上传附件需要合法用户（本平台登录用户）
		if(!JwtFace.isUserLogin(request)){
			result.setCode(Constant.Global.FAIL);
			result.setMessage(Constant.Global.ILLEGAL_ACCESS);
			return result;
		}
		JwtUser su = JwtFace.getJwtUser(request);
		String sysKey = "sys";
		// 转换附件对象
		CommonsMultipartResolver mutilpartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		List<SysAttachment> list = Lists.newArrayList();
		// request如果是Multipart类型
		if (mutilpartResolver.isMultipart(request)) {
			// 强转成 MultipartHttpServletRequest
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取MultipartFile类型文件
			Iterator<String> it = multiRequest.getFileNames();
			while (it != null && it.hasNext()) {
				MultipartFile fileDetail = multiRequest.getFile(it.next());
				if (fileDetail != null) {
					SysAttachment attach = attachmentService.upload(su.getId(), sysKey, relationKey, fileDetail);
					list.add(attach);
				}
			}
		}
		if (Collections3.isEmpty(list)) {
			result.setCode(Constant.Global.FAIL);
			result.setMessage(Constant.Global.UPLOAD_NO_DATA_FOUND);
			return result;
		}
		result.setRows(list);
		result.setSuccess(true);
		result.setCode(Constant.Global.SUCCESS);
		result.setTotal(Long.valueOf(list.size()));
		return result;
	}

	@ApiOperation(value = "附件删除", notes = "该接口必须登录，只能删除自己名下的附件")
	@RequestMapping(value = "upload", method = RequestMethod.DELETE)
	public JsonResult delete(HttpServletRequest request, 
			@ApiParam(value = "附件url", required = true)@RequestParam(value = "url", required = true) String url) {
		JsonResult result = new JsonResult(false);
		// 删除附件只能删除自己的附件，必须登录
		if(!JwtFace.isUserLogin(request)){
			result.setCode(Constant.Global.FAIL);
			result.setMessage(Constant.Global.ILLEGAL_ACCESS);
			return result;
		}
		try {
			if (url.indexOf(",") > 0) {
				for (String u : url.split(",")) {
					attachmentService.delete(JwtFace.getJwtUser(request).getId(), u);
				}
			} else {
				attachmentService.delete(JwtFace.getJwtUser(request).getId(), url);
			}
			result.setSuccess(true);
			result.setCode(Constant.Global.SUCCESS);
			return result;
		} catch (Exception e) {
			result.setCode(Constant.Global.FAIL);
			result.setMessage("删除失败！");
			return result;
		}
	}
	
	@ApiOperation(value = "获取数字字典信息", notes = "该接口已做缓存处理，如有调用其他接口的请使用该接口代替。")
	@RequestMapping(value = "dictionaries", method = RequestMethod.GET)
	public JsonListResult<DictionariesDto> dictionaries(HttpServletRequest request, 
			@ApiParam(value = "字典key", required = true)@RequestParam(value = "key", required = true) String key){
		JsonListResult<DictionariesDto> result = new JsonListResult<DictionariesDto>();
		DictionariesDto dto = basicService.getDictionariesDto(key);
		if(null != dto){
			result.setSuccess(true);
			result.setRows(dto.getSubList());
			result.setCode(Constant.Global.SUCCESS);
			result.setTotal(Long.valueOf(dto.getSubList().size()));
			return result;
		}
		result.setCode(Constant.Global.FAIL);
		return result;
	}
	
	@ApiOperation(value = "umeditor上传图片接口", notes = "该接口仅限umeditor上传使用。")
	@RequestMapping(value = "umUpload", method = RequestMethod.POST)
	public UploadDto umUpload(HttpServletRequest request){
		UploadDto result = new UploadDto();
		
		// 上传附件需要合法用户（本平台登录用户）
		if(!JwtFace.isUserLogin(request)){
			result.setState(UploadDto.allState.get(UploadDto.STATE_UNAUTHORIZED));
			return result;
		}
		JwtUser su = JwtFace.getJwtUser(request);
		String sysKey = "sys";
		// 转换附件对象
		CommonsMultipartResolver mutilpartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		// request如果是Multipart类型
		if (mutilpartResolver.isMultipart(request)) {
			// 强转成 MultipartHttpServletRequest
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取MultipartFile类型文件
			Iterator<String> it = multiRequest.getFileNames();
			while (it != null && it.hasNext()) {
				MultipartFile fileDetail = multiRequest.getFile(it.next());
				if (fileDetail != null) {
					SysAttachment attach = attachmentService.upload(su.getId(), sysKey, "umeditor", fileDetail);
					result.setFileName(attach.getFileName());
					result.setState(UploadDto.allState.get(UploadDto.STATE_SUCCESS));
					result.setOriginalName(attach.getSourceName());
					result.setUrl(attach.getAttachUrl());
					result.setSize(attach.getFileSize());
					result.setType(attach.getFileType());
					result.setSavePath(attach.getFilePath());
					return result;
				}
			}
		}
		result.setState(UploadDto.allState.get(UploadDto.STATE_NOFILE));
		return result;
	}

}
